<?php
/**
 * 系统权限管理控制器
 * @package app\admin\controller
 * User: Administrator
 * Date: 2018/10/22 0013
 * Time: 14:55
 */
namespace app\admin\controller;

use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\Db;
use think\Config;

class Auth extends BasicAdmin
{

    /**
     * 默认数据模型
     * @var string
     */
    public $table = 'SystemAuth';

    /**
     * 权限列表
     */
    public function index(){
        if($this->request->isPost()){
            $params = $this->request->param();
            parent::_list($this->table,$params);
        }
        $this->title = '系统管理 > 权限管理 > 权限管理';
        return $this->fetch('', ['title' => $this->title]);
    }

    protected function _index_data_filter(&$result){
        if(isset($result) && !empty($result)){
            foreach($result as &$v){
                $v['status_str'] = Config::get('auth.status')[$v['status']];
            }
        }
    }

    /**
     * 权限授权
     * @return string
     */
    public function apply()
    {
        $auth_id = $this->request->param('id', '0');
        $method = '_apply_' . strtolower($this->request->param('action', '0'));
        if (method_exists($this, $method)) {
            return $this->$method($auth_id);
        }
        return $this->_form($this->table, 'apply');
    }

    /**
     * 读取授权节点
     * @param $auth_id
     */
    protected function _apply_getnode($auth_id)
    {
        $nodes = NodeService::get();
        $checked = Db::name('SystemAuthNode')->where(['auth' => $auth_id])->column('node');

        foreach ($nodes as &$node) {
            $node['checked'] = in_array($node['node'], $checked);
        }
        $all = $this->_apply_filter(ToolsService::arr2tree($nodes, 'node', 'pnode', '_sub_'));
        $this->success('获取节点成功！', '', $all);
    }

    /**
     * 保存授权节点
     * @param $auth_id
     */
    protected function _apply_save($auth_id)
    {
        list($data, $post) = [[], $this->request->post()];
        foreach (isset($post['nodes']) ? $post['nodes'] : [] as $node) {
            $data[] = ['auth' => $auth_id, 'node' => $node];
        }
        Db::name('SystemAuthNode')->where(['auth' => $auth_id])->delete();
        Db::name('SystemAuthNode')->insertAll($data);
        $this->success('节点授权更新成功！', '');
    }

    /**
     * 节点数据拼装
     * @param array $nodes
     * @param int $level
     * @return array
     */
    protected function _apply_filter($nodes, $level = 1)
    {
        foreach ($nodes as $key => &$node) {
            if (!empty($node['_sub_']) && is_array($node['_sub_'])) {
                $node['_sub_'] = $this->_apply_filter($node['_sub_'], $level + 1);
            }
        }
        return $nodes;
    }

    /**
     * 权限添加
     */
    public function add(){

        return $this->_form($this->table, 'form');
    }

    /**
     * 权限编辑
     */
    public function edit()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 权限状态（1启用 2禁用）
     */
    public function status(){

        $status = $this->request->param('value');
        if (DataService::update($this->table)) {
            $msg = $status == 1 ? '权限启用成功！':'权限禁用成功！';
            $this->result(['status'=>$status],200,$msg,'json');
        }
        $msg = $status == 1 ? '权限启用失败，请稍候再试！':'权限禁用失败，请稍候再试！';
        $f_status = $status == 1 ? 2 : 1;
        $this->result(['status'=>$f_status],0,$msg,'json');
    }

    /**
     * 权限删除
     */
    public function del(){
        if (DataService::update($this->table)) {
            $id = $this->request->post('id');
            Db::name('SystemAuthNode')->where(['auth' => $id])->delete();
            $this->result([],200,'权限删除成功！','json');
        }
        $this->result([],0,'权限删除失败，请稍候再试！','json');
    }

}
